package com.coursehub.exercise.repository;

import com.coursehub.exercise.entity.ExerciseQuestion;
import com.coursehub.exercise.entity.ExerciseQuestionId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 练习题目关联数据访问层
 */
@Repository
public interface ExerciseQuestionRepository extends JpaRepository<ExerciseQuestion, ExerciseQuestionId> {
    
    /**
     * 根据练习ID查询所有关联的题目
     * @param exerciseId 练习ID
     * @return 练习题目关联列表
     */
    List<ExerciseQuestion> findByIdExerciseId(String exerciseId);
    
    /**
     * 根据题目ID查询所有关联的练习
     * @param questionId 题目ID
     * @return 练习题目关联列表
     */
    List<ExerciseQuestion> findByIdQuestionId(String questionId);
    
    /**
     * 查询练习下的题目ID列表
     * @param exerciseId 练习ID
     * @return 题目ID列表
     */
    @Query("SELECT eq.id.questionId FROM ExerciseQuestion eq WHERE eq.id.exerciseId = :exerciseId")
    List<String> findQuestionIdsByExerciseId(@Param("exerciseId") String exerciseId);
    
    /**
     * 查询题目关联的练习ID列表
     * @param questionId 题目ID
     * @return 练习ID列表
     */
    @Query("SELECT eq.id.exerciseId FROM ExerciseQuestion eq WHERE eq.id.questionId = :questionId")
    List<String> findExerciseIdsByQuestionId(@Param("questionId") String questionId);
    
    /**
     * 检查练习和题目的关联是否存在
     * @param exerciseId 练习ID
     * @param questionId 题目ID
     * @return 是否存在关联
     */
    boolean existsByIdExerciseIdAndIdQuestionId(String exerciseId, String questionId);
    
    /**
     * 删除练习的所有题目关联
     * @param exerciseId 练习ID
     */
    void deleteByIdExerciseId(String exerciseId);
    
    /**
     * 删除题目的所有练习关联
     * @param questionId 题目ID
     */
    void deleteByIdQuestionId(String questionId);
}